package com;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.naming.NamingException;

import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.domain.Chatter;

@Service
public class NicknameValidation {
	String nickname;
	boolean value;

	@Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Transactional
	public boolean validate(String name) throws IOException, SQLException, NamingException {
		String query = "SELECT nickname FROM users WHERE nickname=:nickname;";
		String queryUpdate = "INSERT INTO users(nickname) VALUES(:nickname);";

		ParameterizedRowMapper<Chatter> mapper = new ParameterizedRowMapper<Chatter>() {
			public Chatter mapRow(ResultSet rs, int rowNum) throws SQLException {
				Chatter chatter = new Chatter(rs.getString("nickname"));
				return chatter;
			}
		};
		if (name != null) {
            Map namedParameters = new HashMap();
            namedParameters.put("nickname", name);
			List<Chatter> chatters = (List<Chatter>) namedParameterJdbcTemplate.query(query, namedParameters, mapper);
			if (!chatters.isEmpty()) {
				value = false;
			} else {
				value = true;
                namedParameterJdbcTemplate.update(queryUpdate, namedParameters);
			}
		}
		return value;
	}
}
